package cn.codeinn.common.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Sets;

import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;

public class SwaggerBasic {
	private List<SecurityScheme> mySchemes() {
		List<SecurityScheme> schemes = new ArrayList<>();
		schemes.add(new ApiKey("Authorization", "Authorization", "header"));
		return schemes;
	}

	private List<SecurityContext> myContexts() {
		AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
		AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
		authorizationScopes[0] = authorizationScope;
		List<SecurityReference> references = new ArrayList<>();
		references.add(new SecurityReference("Authorization", authorizationScopes));

		List<SecurityContext> contexts = new ArrayList<>();
		contexts.add(SecurityContext.builder().securityReferences(references).forPaths(PathSelectors.regex("^((?!login).)*$")).build());
		return contexts;
	}

	private HashSet<String> myMessage() {
		return Sets.newHashSet("application/json");
	}

	public ApiInfo apiInfo() {
		ApiInfo apiInfo = new ApiInfoBuilder().title("接口文档").description("文档中可以查询及测试接口调用参数和结果").version("1.0.0").build();
		return apiInfo;
	}

	public Docket docket(Predicate<String> predicate, String path, Predicate<RequestHandler> basePackage) {
		ApiSelectorBuilder apiSelectorBuilder = new Docket(DocumentationType.SWAGGER_2).produces(myMessage()).consumes(myMessage()).select();
		apiSelectorBuilder.paths(Predicates.not(PathSelectors.regex("/error.*")));
		apiSelectorBuilder.paths(Predicates.not(PathSelectors.regex("/actuator.*")));
		apiSelectorBuilder.apis(RequestHandlerSelectors.any()).paths(predicate);
		return apiSelectorBuilder.build().pathMapping(path).apiInfo(apiInfo()).securitySchemes(mySchemes()).securityContexts(myContexts());
	}

}
